package com.spirngboot.middleware.middleware_rabbitmq.server.rabbitmq.simple;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class Consumer {
    private static final Logger log = LoggerFactory.getLogger(Producer.class);

    public static void main(String[] args) {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("120.24.87.40");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("root");
        connectionFactory.setPassword("Guet@207");
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接Connection
            String connectName = "消费者";
            connection = connectionFactory.newConnection(connectName);
            log.info("创建连接成功,连接名:{},连接:{}", connectName, connection.toString());
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            log.info("创建通道成功,通道名:{}", channel.toString());
            //4.通过创建交换机,声明队列,绑定关系,路由key,发送信息和接收信息
            String queueName = "queue1";
            log.info("创建channel成功并声明队列,队列名{},所用chanel:{}", queueName, channel.toString());

            channel.basicConsume(queueName, true,
                    (consumerTag, message) -> System.out.println("收到的消息是" + new String(message.getBody(), StandardCharsets.UTF_8)),
                    consumerTag -> System.out.println("接收失败了")
            );
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7.关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //8.关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
